<!DOCTYPE html>





<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    save_scroll: false,
    copycode: {"enable":false,"show_result":false,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="Linux进程间通信之管道什么是管道？管道是一种最基本的IPC机制，作用于有血缘关系的进程之间，完成数据传递。调用pipe系统函数即可创建一个管道。  其本质是一个伪文件(实为内核缓冲区)  由两个文件描述符引用，一个表示读端，一个表示写端。  规定数据从管道的写端流入管道，从读端流出。   管道的原理:  管道实为内核使用环形队列机制，借助内核缓冲区(4k)实现。 例如:  1ps -ef |">
<meta name="keywords" content="Linux管道pipe">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux管道pipe">
<meta property="og:url" content="http://yoursite.com/2019/08/14/Linux管道pipe/index.html">
<meta property="og:site_name" content="XuQi&#39;s Blog">
<meta property="og:description" content="Linux进程间通信之管道什么是管道？管道是一种最基本的IPC机制，作用于有血缘关系的进程之间，完成数据传递。调用pipe系统函数即可创建一个管道。  其本质是一个伪文件(实为内核缓冲区)  由两个文件描述符引用，一个表示读端，一个表示写端。  规定数据从管道的写端流入管道，从读端流出。   管道的原理:  管道实为内核使用环形队列机制，借助内核缓冲区(4k)实现。 例如:  1ps -ef |">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/2019/08/14/Linux管道pipe/image-20190814221735897.png">
<meta property="og:updated_time" content="2019-10-20T13:23:23.041Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Linux管道pipe">
<meta name="twitter:description" content="Linux进程间通信之管道什么是管道？管道是一种最基本的IPC机制，作用于有血缘关系的进程之间，完成数据传递。调用pipe系统函数即可创建一个管道。  其本质是一个伪文件(实为内核缓冲区)  由两个文件描述符引用，一个表示读端，一个表示写端。  规定数据从管道的写端流入管道，从读端流出。   管道的原理:  管道实为内核使用环形队列机制，借助内核缓冲区(4k)实现。 例如:  1ps -ef |">
<meta name="twitter:image" content="http://yoursite.com/2019/08/14/Linux管道pipe/image-20190814221735897.png">
  <link rel="canonical" href="http://yoursite.com/2019/08/14/Linux管道pipe/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Linux管道pipe | XuQi's Blog</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">XuQi's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
  </ul>

    

</nav>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/08/14/Linux管道pipe/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="XuQi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="XuQi's Blog">
    </span>
      <header class="post-header">

        
          <h1 class="post-title" itemprop="name headline">Linux管道pipe

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-08-14 22:06:55" itemprop="dateCreated datePublished" datetime="2019-08-14T22:06:55+00:00">2019-08-14</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-20 13:23:23" itemprop="dateModified" datetime="2019-10-20T13:23:23+00:00">2019-10-20</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="Linux进程间通信之管道"><a href="#Linux进程间通信之管道" class="headerlink" title="Linux进程间通信之管道"></a>Linux进程间通信之管道</h2><h3 id="什么是管道？"><a href="#什么是管道？" class="headerlink" title="什么是管道？"></a>什么是管道？</h3><p>管道是一种最基本的IPC机制，作用于有血缘关系的进程之间，完成数据传递。调用pipe系统函数即可创建一个管道。</p>
<ol>
<li><p>其本质是一个伪文件(实为内核缓冲区)</p>
</li>
<li><p>由两个文件描述符引用，一个表示读端，一个表示写端。</p>
</li>
<li><p>规定数据从管道的写端流入管道，从读端流出。</p>
</li>
</ol>
<p><strong>管道的原理:</strong> </p>
<p>管道实为内核使用环形队列机制，借助内核缓冲区(4k)实现。</p>
<p>例如: </p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -ef | grep init</span><br></pre></td></tr></table></figure>

<p><strong>管道的局限性：</strong></p>
<p>① 数据自己读不能自己写。</p>
<p>② 数据一旦被读走，便不在管道中存在，不可反复读取。</p>
<p>③ 由于管道采用半双工通信方式。因此，数据只能在一个方向上流动。</p>
<p>④ <strong>只能在有公共祖先的进程间使用管道。</strong></p>
<h4 id="pipe调用"><a href="#pipe调用" class="headerlink" title="pipe调用"></a>pipe调用</h4><h5 id="创建管道"><a href="#创建管道" class="headerlink" title="创建管道"></a>创建管道</h5><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pipe</span><span class="params">(<span class="keyword">int</span> pipefd[<span class="number">2</span>])</span></span>; 成功：<span class="number">0</span>；失败：<span class="number">-1</span>，设置errno</span><br></pre></td></tr></table></figure>

<p>函数调用成功返回r/w两个文件描述符。无需open，但需手动close。规定：fd[0] → r； fd[1] → w，就像0对应标准输入，1对应标准输出一样。向管道文件读写数据其实是在读写内核缓冲区。</p>
<p>管道创建成功以后，创建该管道的进程（父进程）同时掌握着管道的读端和写端。如何实现父子进程间通信呢？通常可以采用如下步骤：</p>
<p><img src="/2019/08/14/Linux管道pipe/image-20190814221735897.png" alt="image-20190814221735897"></p>
<h5 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h5><ol>
<li>父进程调用pipe函数创建管道，得到两个文件描述符fd[0]、fd[1]指向管道的读端和写端。</li>
<li>父进程调用fork创建子进程，那么子进程也有两个文件描述符指向同一管道。</li>
<li>父进程关闭管道读端，子进程关闭管道写端。父进程可以向管道中写入数据，子进程将管道中的数据读出。由于管道是利用环形队列实现的，数据从写端流入管道，从读端流出，这样就实现了进程间通信。</li>
</ol>
<h5 id="管道的读写行为"><a href="#管道的读写行为" class="headerlink" title="管道的读写行为"></a>管道的读写行为</h5><p>使用管道需要注意以下4种特殊情况（<strong>假设都是阻塞I/O操作</strong>，没有设置O_NONBLOCK标志）：</p>
<ol>
<li><p>如果所有指向管道<strong>写端的文件描述符都关闭了</strong>（管道写端引用计数为0），而仍然有进程从管道的读端读数据，那么管道中剩余的数据都被读取后，再次read会返回0，就像读到文件末尾一样。</p>
</li>
<li><p>如果有指向管道<strong>写端的文件描述符没关闭</strong>（管道写端引用计数大于0），而持有管道写端的进程也没有向管道中写数据，这时有进程从管道读端读数据，那么管道中剩余的数据都被读取后，再次read会阻塞，直到管道中有数据可读了才读取数据并返回。</p>
</li>
<li><p>如果所有指向管道<strong>读端的文件描述符都关闭了</strong>（管道读端引用计数为0），这时有进程向管道的写端write，那么该进程会收到信号SIGPIPE，<strong>通常会导致进程异常终止</strong>。当然也可以对SIGPIPE信号实施捕捉，不终止进程。具体方法信号章节详细介绍。</p>
</li>
<li><p>如果有指向管道<strong>读端的文件描述符没关闭</strong>（管道读端引用计数大于0），而持有管道读端的进程也没有从管道中读数据，这时有进程向管道写端写数据，那么在管道被写满时再次write会阻塞，直到管道中有空位置了才写入数据并返回。</p>
</li>
</ol>
<h5 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h5><p>① 读管道：</p>
<ol>
<li>管道中有数据，read返回实际读到的字节数。</li>
</ol>
<ol start="2">
<li><p>管道中无数据：</p>
<p>(1) 管道写端被全部关闭，read返回0 (好像读到文件结尾)</p>
<p>(2) 写端没有全部被关闭，read阻塞等待(不久的将来可能有数据递达，此时会让出cpu)</p>
</li>
</ol>
<p>② 写管道：</p>
<ol>
<li>管道读端全部被关闭， 进程异常终止(也可使用捕捉SIGPIPE信号，使进程不终止)</li>
</ol>
<ol start="2">
<li><p>管道读端没有全部关闭：</p>
<p>(1) 管道已满，write阻塞。</p>
<p>(2) 管道未满，write将数据写入，并返回实际写入的字节数。</p>
</li>
</ol>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/Linux管道pipe/" rel="tag"># Linux管道pipe</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/08/03/树莓派交叉编译/" rel="next" title="树莓派交叉编译">
                  <i class="fa fa-chevron-left"></i> 树莓派交叉编译
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/08/20/GPS基础知识/" rel="prev" title="GPS基础知识">
                  GPS基础知识 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">XuQi</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">44</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">30</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Linux进程间通信之管道"><span class="nav-number">1.</span> <span class="nav-text">Linux进程间通信之管道</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是管道？"><span class="nav-number">1.1.</span> <span class="nav-text">什么是管道？</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#pipe调用"><span class="nav-number">1.1.1.</span> <span class="nav-text">pipe调用</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#创建管道"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">创建管道</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#步骤"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">步骤</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#管道的读写行为"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">管道的读写行为</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#总结："><span class="nav-number">1.1.1.4.</span> <span class="nav-text">总结：</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">XuQi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> v7.3.0</div>

        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>
  <script src="/js/motion.js?v=7.3.0"></script>


  <script src="/js/schemes/muse.js?v=7.3.0"></script>


<script src="/js/next-boot.js?v=7.3.0"></script>




  




























  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>


</body>
</html>
